package com.zoe.onelink.governance.gateway.route.generator;

import com.alibaba.nacos.api.config.ConfigType;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import com.zoe.onelink.governance.gateway.model.NativeGatewayRoute;
import com.zoe.onelink.governance.gateway.serializer.GatewayRouteParamSerializer;
import org.springframework.boot.convert.DurationStyle;

import java.io.IOException;
import java.time.Duration;
import java.util.Optional;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-11-10
 */
class GatewayDynamicRouteGeneratorTestUtil {

    private static final SimpleModule simpleModule = new SimpleModule()
            .addSerializer(NativeGatewayRoute.GatewayRouteParam.class, new GatewayRouteParamSerializer())
            .addDeserializer(Duration.class, new SpringDurationStyleDeserializer());

    static ObjectMapper getObjectMapper(ConfigType configType) {
        ObjectMapper objectMapper = ConfigType.YAML == configType ? new YAMLMapper() : new ObjectMapper();
        return objectMapper.registerModule(simpleModule)
                .setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
    }

    static class SpringDurationStyleDeserializer extends JsonDeserializer<Duration> {
        @Override
        public Duration deserialize(JsonParser jsonParser, DeserializationContext __) throws IOException {
            return Optional.ofNullable(jsonParser.getText()).map(DurationStyle::detectAndParse).orElse(null);
        }
    }
}
